﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using System.Web.Security;

public partial class Admin_EditUser : BasePage
{
    private string username = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        username = this.Request.QueryString["UserName"];

        lblRolesFeedbackOK.Visible = false;

        if (!IsPostBack)
        {
            MembershipUser user = Membership.GetUser(username);
            lblUserName.Text = user.UserName;
            lnkEmail.Text = user.Email;
            lnkEmail.NavigateUrl = "mailto:" + user.Email;
            lblRegistered.Text = user.CreationDate.ToString("f");
            lblLastLogin.Text = user.LastLoginDate.ToString("f");
            lblLastActivity.Text = user.LastActivityDate.ToString("f");
            chkOnlineNow.Checked = user.IsOnline;
            chkApproved.Checked = user.IsApproved;
            chkLockedOut.Checked = user.IsLockedOut;
            chkLockedOut.Enabled = user.IsLockedOut;

            BindRole();
        }
    }
    private void BindRole()
    {
        chklRoles.DataSource = Roles.GetAllRoles();
        chklRoles.DataBind();

        foreach (string role in Roles.GetRolesForUser(username))
            chklRoles.Items.FindByText(role).Selected = true;
    }


    protected void chkLockedOut_CheckedChanged(object sender, EventArgs e)
    {
        if (chkLockedOut.Checked == false)
        {
            MembershipUser user = Membership.GetUser(username);
            user.UnlockUser();
            chkLockedOut.Enabled = false;
        }
    }
    protected void chkApproved_CheckedChanged(object sender, EventArgs e)
    {
        MembershipUser user = Membership.GetUser(username);
        user.IsApproved = chkApproved.Checked;
        Membership.UpdateUser(user);
    }
    protected void btnUpdateRoles_Click(object sender, EventArgs e)
    {
        string[] roles = Roles.GetRolesForUser(username);
        if (roles.Length > 0)
            Roles.RemoveUserFromRoles(username, roles);

        List<string> newRoles = new List<string>();
        foreach (ListItem item in chklRoles.Items)
        {
            if (item.Selected)
                newRoles.Add(item.Text);
        }
        Roles.AddUserToRoles(username, newRoles.ToArray());

        lblRolesFeedbackOK.Visible = true;

    }
}
